Telegram Group & Telegram Channel
Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5



tg-me.com/cpluspluc/1026
Create:
Last Update:

Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1026

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

How Does Bitcoin Work?

Bitcoin is built on a distributed digital record called a blockchain. As the name implies, blockchain is a linked body of data, made up of units called blocks that contain information about each and every transaction, including date and time, total value, buyer and seller, and a unique identifying code for each exchange. Entries are strung together in chronological order, creating a digital chain of blocks. “Once a block is added to the blockchain, it becomes accessible to anyone who wishes to view it, acting as a public ledger of cryptocurrency transactions,” says Stacey Harris, consultant for Pelicoin, a network of cryptocurrency ATMs. Blockchain is decentralized, which means it’s not controlled by any one organization. “It’s like a Google Doc that anyone can work on,” says Buchi Okoro, CEO and co-founder of African cryptocurrency exchange Quidax. “Nobody owns it, but anyone who has a link can contribute to it. And as different people update it, your copy also gets updated.”

That growth environment will include rising inflation and interest rates. Those upward shifts naturally accompany healthy growth periods as the demand for resources, products and services rise. Importantly, the Federal Reserve has laid out the rationale for not interfering with that natural growth transition.It's not exactly a fad, but there is a widespread willingness to pay up for a growth story. Classic fundamental analysis takes a back seat. Even negative earnings are ignored. In fact, positive earnings seem to be a limiting measure, producing the question, "Is that all you've got?" The preference is a vision of untold riches when the exciting story plays out as expected.

C Academy from tw


Telegram C++ Academy
FROM USA